package com.onurokan.someone4me.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.multipart.MultipartFile;

import com.onurokan.someone4me.photo.domain.Photo;

public class PhotoValidator implements Validator{

	private static final long MAX_SIZE = 10 * 1024 *1024; // 10MB
	public boolean supports(Class clazz) {
		//just validate the FileUpload instances
		return Photo.class.isAssignableFrom(clazz);
	}
 
	public void validate(Object object, Errors errors) {
		Photo photo = (Photo)object;
		MultipartFile file = photo.getFile();
		long fileSize = file.getSize();
		if(fileSize == 0){
			errors.rejectValue("file", "Min.fileUpload.file");
		} else if (fileSize > MAX_SIZE) {
			errors.rejectValue("file", "Max.fileUpload.file");
		} else if (!file.getContentType().startsWith("image/")) {
			errors.rejectValue("file", "NotImage.fileUpload.file");
		}
	}

}
